package com.dating.base.service;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.dating.base.bean.Permission;
import com.dating.base.bean.User;
import com.dating.base.bean.UserPermission;
import com.dating.base.dao.UserPermissionDao;

@IocBean
public class UserPermissionService {

	@Inject
	private Dao dao ;
	
	@Inject
	private UserPermissionDao userPermissionDao;
	
	
	/**
	 * 根据用户获取拥有的权限
	 * @param userPer
	 * @return
	 */
	public List<Permission> getPermissions(UserPermission userPer){
		User user = new User();
		user.setId(userPer.getUserId());
		user.setUserType(userPer.getType());
		return userPermissionDao.getPermissions(user);
	}
	
	
	/**
	 * 更新用户权限
	 * @param userPer
	 */
	public void save(UserPermission userPer){
		Cnd cnd = Cnd.where("userId","=", userPer.getUserId());
		cnd.and("permissionId", "=", userPer.getPermissionId());
		cnd.and("type", "=", userPer.getType().name());
		UserPermission up = userPermissionDao.findByCondition(cnd);
		if(up == null){
			userPermissionDao.save(userPer);
		}else{
			userPer.setId(up.getId());
			userPermissionDao.update(userPer);
		}
	}
	
	/**
	 * 
	 * @param userPer
	 * @param status
	 */
	public void setPermission(UserPermission userPer ,String status){
		if("Y".equals(status)){
			save(userPer);
		}
		if("N".equals(status)){
			Cnd cnd = Cnd.where("userId","=", userPer.getUserId());
			cnd.and("permissionId", "=", userPer.getPermissionId());
			cnd.and("type", "=", userPer.getType().name());
			dao.clear(UserPermission.class, cnd);
		}
	}
	
}
